<?php
/**
 * 检验签名中间件
 */

namespace App\middleware;

use app\service\GameService;
use support\Common;
use support\ErrorCode;
use support\Log;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class CheckSign implements MiddlewareInterface
{
    //时间范围
    const TIME_RANGE = 3600;
    const SALT_KEY = "c55f4ca244f22f3554cb91668f5dc8d5";
    const AES_KEY = 'mMjm1073EGWacbjJ';
    const AES_IV = '1234567890123456';

    public function process(Request $request, callable $handler): Response
    {
        // 请求继续向洋葱芯穿越
        $params = $request->post();
        $request->postData = $params;
        if (empty($params)) {
            $params = $request->rawBody();
            $params = self::decryptAES($params, self::AES_KEY, self::AES_IV);
            $params = json_decode($params, true);
            $request->postData = $params;
        }

        // 请求继续向洋葱芯穿越
        Common::writeLog($params, __FILE__, __FUNCTION__, __LINE__);

        //        var_dump(getenv("APP_ENV"));
        if (getenv("APP_ENV") != 'production') {
            return $handler($request);
        }

        if (empty($params["sign"])) {
            return outJson(1, '签名验证失败');
        }

        $sign = self::makeSignPretreat($params, self::SALT_KEY);

        //如果签名不正确l
        if ($sign != $params['sign']) {
            Common::writeLog([$params, '签名验证失败!'], __FILE__, __FUNCTION__, __LINE__);
            return outJson(1, '签名验证失败');
        }

        return $handler($request);
    }

    public static function makeSignPretreat($data, $signKey)
    {
        unset($data['sign']);

        ksort($data); //键按a-z升序

        $rSign = '';
        foreach ($data as $key => $val) {
            $rSign .= $key . '=' . $val . '&';
        }
        //        $rSign = rtrim($rSign, '&');
        $rSign .= $signKey;
        echo $rSign;
        return md5($rSign);
    }


    public static function encryptAES($data, $key, $iv)
    {
        $encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }

    public static function decryptAES($data, $key, $iv)
    {
        $decrypted = openssl_decrypt(base64_decode($data), 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv);
        if ($decrypted === false) {
            echo "解密失败，错误信息：";
            // 打印错误信息
            $errorMsg = openssl_error_string();
            echo $errorMsg;
            // 根

        }
        return $decrypted;
    }


}